from rest_framework.permissions import DjangoModelPermissions, IsAdminUser

from apps.goods.models import SKUImage,SKU
from rest_framework.viewsets import ModelViewSet
from rest_framework.generics import ListAPIView
from apps.wthg_admin.serializers.images import SKUImageModelSerializer,SKUImagePageNumberPagination,SKUModelSerializer
from rest_framework import status
from rest_framework.views import Response
from fdfs_client import client


class SKUImageModelViewSet(ModelViewSet):
    """商品图片增删改查"""
    queryset =SKUImage.objects.all()
    serializer_class = SKUImageModelSerializer
    pagination_class = SKUImagePageNumberPagination


    def create(self, request, *args, **kwargs):
        """增加图片"""
        # 接受数据
        sku_id=request.data.get('sku')
        image=request.data.get('image')
        # 验证数据
        try:
            SKU.objects.get(id=sku_id)
        except Exception:
            return Response({'error':'该商品不存在'},status=status.HTTP_400_BAD_REQUEST)

        if image is None or image == '':
            return Response({'error': '图片传输有误'},status=status.HTTP_400_BAD_REQUEST)

        image=image.read()  # 读取图片二进制数据流
        # 数据保存
            # 保存到fastdfs服务器
        cli=client.Fdfs_client('utils/fastdfs/client.conf')
        imagedate=cli.upload_by_buffer(image)

        """
        {'Remote file_id': 'group1/M00/00/00/wKjlhFsTgJ2AJvG_AAAyZgOTZN0850.jpg', 
        'Uploaded size': '12.00KB',
        'Local file name': '/home/python/Desktop/images/0.jpg',
        'Storage IP': '192.168.229.132',
        'Group name': 'group1', 
        'Status': 'Upload successed.'}
        """
            #验证fastdfs服务器保存是否成功
        if imagedate['Status'] != 'Upload successed.' or len(imagedate['Remote file_id']) < 5:
            return Response({'error': 'fastdfs服务器保存失败'},status=status.HTTP_400_BAD_REQUEST)
            # 保存图片路径到mysql
        SKUImage.objects.create(image=imagedate['Remote file_id'],sku_id=sku_id)
        # 响应数据
        return Response(status=status.HTTP_200_OK)




class SKUListAPIView(ListAPIView):
    """增加图片查询sku_id"""
    queryset = SKU.objects.all()
    serializer_class = SKUModelSerializer



